package controllers

import (
	"supershare/backend/middleware"
	"supershare/backend/models"

	"fmt"
	"time"

	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/server/web"
)

// MemberPointsController 处理会员积分记录相关请求
type MemberPointsController struct {
	web.Controller
}

// List 获取会员积分变动记录列表
func (c *MemberPointsController) List() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 解析分页参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("page_size", 10)

	// 解析过滤条件
	filters := make(map[string]interface{})

	// 会员ID
	if memberId, err := c.GetInt64("member_id", 0); err == nil && memberId > 0 {
		filters["member_id"] = memberId
	}

	// 积分变动类型
	if logType, err := c.GetInt8("type", -1); err == nil && logType != -1 {
		filters["type"] = logType
	}

	// 订单号
	if orderNo := c.GetString("order_no"); orderNo != "" {
		filters["order_no"] = orderNo
	}

	// 时间范围
	if startTime, err := c.GetInt64("start_time", 0); err == nil && startTime > 0 {
		filters["start_time"] = startTime
	}

	if endTime, err := c.GetInt64("end_time", 0); err == nil && endTime > 0 {
		filters["end_time"] = endTime
	}

	// 加盟商过滤
	if admin.FranchiseId > 0 {
		filters["franchise_id"] = admin.FranchiseId
	}

	// 获取积分变动记录列表
	pointsLogs, total, err := models.GetPointsLogList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取积分变动记录列表失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回积分变动记录列表
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取积分变动记录列表成功",
		"data": map[string]interface{}{
			"list":  pointsLogs,
			"total": total,
			"page":  page,
			"size":  pageSize,
		},
	}
	c.ServeJSON()
}

// Detail 获取积分变动记录详情
func (c *MemberPointsController) Detail() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取记录ID
	id, err := c.GetInt64("id")
	if err != nil || id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的记录ID",
		}
		c.ServeJSON()
		return
	}

	// 获取积分变动记录详情，带加盟商权限验证
	pointsLog, err := models.GetPointsLogById(id, admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取积分变动记录详情失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 获取关联会员信息
	member, err := models.GetMemberById(pointsLog.MemberId, admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取会员信息失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回积分变动记录详情
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取积分变动记录详情成功",
		"data": map[string]interface{}{
			"log":    pointsLog,
			"member": member,
		},
	}
	c.ServeJSON()
}

// AdjustPoints 调整会员积分
func (c *MemberPointsController) AdjustPoints() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取会员ID
	memberId, err := c.GetInt64("member_id")
	if err != nil || memberId <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的会员ID",
		}
		c.ServeJSON()
		return
	}

	// 获取调整积分
	points, err := c.GetInt("points")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的调整积分",
		}
		c.ServeJSON()
		return
	}

	// 获取调整原因
	description := c.GetString("description")
	if description == "" {
		description = "管理员积分调整"
	}

	// 获取会员信息，验证会员是否属于该加盟商
	member, err := models.GetMemberById(memberId, admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "会员不存在或不属于该加盟商",
		}
		c.ServeJSON()
		return
	}

	// 检查调整后的积分是否小于0
	if member.Points+points < 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "调整后积分不能小于0",
		}
		c.ServeJSON()
		return
	}

	// 调整会员积分
	err = models.AddMemberPoints(
		memberId,
		points,
		2, // 2:管理员调整
		"",
		description,
		admin.Username,
		admin.FranchiseId,
	)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "调整会员积分失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 记录操作日志
	models.CreateOperationLog(
		admin.Id,
		"调整会员积分",
		fmt.Sprintf("调整会员ID:%d的积分，积分:%d，原因:%s", memberId, points, description),
		c.Ctx.Request.Method,
		c.Ctx.Input.IP(),
		admin.FranchiseId,
	)

	// 返回成功信息
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "调整会员积分成功",
	}
	c.ServeJSON()
}

// Stats 获取积分统计信息
func (c *MemberPointsController) Stats() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 计算各种统计数据，需要加盟商权限过滤
	o := orm.NewOrm()

	// 统计今日积分变动和总积分
	today := time.Now().Format("2006-01-02")
	startTime := time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, time.Local).Unix()
	endTime := time.Now().Unix()

	// 今日积分变动统计
	var todayAddPoints int64
	var todayReducePoints int64
	var totalPoints int64
	var memberCount int64

	// 如果是加盟商管理员，需要过滤数据
	if admin.FranchiseId > 0 {
		// 获取该加盟商下的所有会员ID
		var memberIds orm.ParamsList
		_, err := o.QueryTable(new(models.Member)).
			Filter("franchise_id", admin.FranchiseId).
			Filter("is_deleted", 0).
			ValuesFlat(&memberIds, "id")
		if err != nil || len(memberIds) == 0 {
			// 没有会员，返回空数据
			c.Data["json"] = map[string]interface{}{
				"success": true,
				"message": "获取积分统计信息成功",
				"data": map[string]interface{}{
					"today_add_points":    0,
					"today_reduce_points": 0,
					"total_points":        0,
					"member_count":        0,
				},
			}
			c.ServeJSON()
			return
		}

		// 今日增加积分统计
		err = o.Raw(`
			SELECT IFNULL(SUM(points), 0) as total_points 
			FROM ss_points_log 
			WHERE member_id IN (?) AND points > 0 AND created_at BETWEEN ? AND ? AND is_deleted = 0
		`, memberIds, startTime, endTime).QueryRow(&todayAddPoints)

		// 今日减少积分统计
		err = o.Raw(`
			SELECT IFNULL(SUM(ABS(points)), 0) as total_points 
			FROM ss_points_log 
			WHERE member_id IN (?) AND points < 0 AND created_at BETWEEN ? AND ? AND is_deleted = 0
		`, memberIds, startTime, endTime).QueryRow(&todayReducePoints)

		// 总积分统计
		err = o.Raw(`
			SELECT IFNULL(SUM(points), 0) as total_points, COUNT(*) as count 
			FROM ss_member 
			WHERE franchise_id = ? AND is_deleted = 0
		`, admin.FranchiseId).QueryRow(&totalPoints, &memberCount)
	} else {
		// 平台管理员，查看所有数据
		err = o.Raw(`
			SELECT IFNULL(SUM(points), 0) as total_points 
			FROM ss_points_log 
			WHERE points > 0 AND created_at BETWEEN ? AND ? AND is_deleted = 0
		`, startTime, endTime).QueryRow(&todayAddPoints)

		err = o.Raw(`
			SELECT IFNULL(SUM(ABS(points)), 0) as total_points 
			FROM ss_points_log 
			WHERE points < 0 AND created_at BETWEEN ? AND ? AND is_deleted = 0
		`, startTime, endTime).QueryRow(&todayReducePoints)

		err = o.Raw(`
			SELECT IFNULL(SUM(points), 0) as total_points, COUNT(*) as count 
			FROM ss_member 
			WHERE is_deleted = 0
		`).QueryRow(&totalPoints, &memberCount)
	}

	// 返回统计数据
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取积分统计信息成功",
		"data": map[string]interface{}{
			"today_add_points":    todayAddPoints,
			"today_reduce_points": todayReducePoints,
			"total_points":        totalPoints,
			"member_count":        memberCount,
			"date":                today,
		},
	}
	c.ServeJSON()
}
